package com.kalaqia.im.library.room;

import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMChatRoomManager;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.MainThreadDisposable;

/**
 * function:
 * project:kalaqia
 * describe:
 * created owner:kalaqia 421407393@qq.com
 * created date:2017/8/16 16:04
 */
//<editor-fold desc="version update log">
// updare owner:kalaqia  421407393@qq.com
// update datetime:2017/8/16 16:04 
// update remark:
//</editor-fold>
public class EMChatRoomJoinObservable extends Observable<EMChatRoom> {

    private EMChatRoomManager manager;
    private String roomId;

    public EMChatRoomJoinObservable(EMChatRoomManager manager, String roomId) {
        this.manager = manager;
        this.roomId = roomId;
    }

    @Override
    protected void subscribeActual(Observer<? super EMChatRoom> observer) {
        EMChatRoomJoinDisposable disposable = new EMChatRoomJoinDisposable(observer);
        observer.onSubscribe(disposable);
        manager.joinChatRoom(roomId, disposable);
    }

    private final class EMChatRoomJoinDisposable extends MainThreadDisposable implements EMValueCallBack<EMChatRoom> {

        private final Observer<? super EMChatRoom> observer;

        public EMChatRoomJoinDisposable(Observer<? super EMChatRoom> observer) {
            this.observer = observer;
        }

        @Override
        public void onSuccess(EMChatRoom emChatRoom) {
            if (!isDisposed()) {
                observer.onNext(emChatRoom);
            }
        }

        @Override
        public void onError(int i, String s) {
            if (!isDisposed()) {
                observer.onError(new Throwable(s));
            }
        }

        @Override
        protected void onDispose() {

        }

    }


}
